<template>
    <div class="app-container">
      <div class="filter-container">
        <el-autocomplete
          v-model="listQuery.cityName"
          :fetch-suggestions="loadCities"
          placeholder="请选择城市"
          class="filter-item"
          @select="handleSelect">
        </el-autocomplete>
  
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          Search
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          Add
        </el-button>
      </div>
  
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="ID" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
        <el-table-column label="城市" prop="cityCode" align="center">
          <template slot-scope="{row}">
            <span>{{ getCityName(row.cityCode) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车辆类型" prop="vehicleType" align="center">
          <template slot-scope="{row}">
            <span>{{ getCarType(row.vehicleType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="起步价" prop="startFare" align="center">
          <template slot-scope="{row}">
            <span>{{ row.startFare }}</span>
          </template>
        </el-table-column>
        <el-table-column label="起步公里" prop="startMile" align="center">
          <template slot-scope="{row}">
            <span>{{ row.startMile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="每公里加价" prop="unitPricePerMile" align="center">
          <template slot-scope="{row}">
            <span>{{ row.unitPricePerMile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="每分钟加价" prop="unitPricePerMinute" align="center">
          <template slot-scope="{row}">
            <span>{{ row.unitPricePerMinute }}</span>
          </template>
        </el-table-column>
        <el-table-column label="版本" prop="fareVersion" align="center">
          <template slot-scope="{row}">
            <span>{{ row.fareVersion }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              Edit
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
              Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
          <el-form-item v-if="dialogStatus === 'create'" label="城市" prop="cityCode">
            <el-autocomplete
              v-model="temp.cityName"
              :fetch-suggestions="loadCities"
              placeholder="请选择城市"
              class="filter-item"
              @select="handleSelectUpdate">
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="车辆类型" prop="vehicleType">
            <el-radio-group v-model="temp.vehicleType">
              <el-radio :label="'1'">轿车</el-radio>
              <el-radio :label="'2'">SUV</el-radio>
              <el-radio :label="'3'">MPV</el-radio>
              <el-radio :label="'4'">面包车</el-radio>
              <el-radio :label="'9'">其他</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="起步价" prop="startFare">
            <el-input v-model="temp.startFare" />
          </el-form-item>
          <el-form-item label="起步公里" prop="startMile">
            <el-input v-model="temp.startMile" />
          </el-form-item>
          <el-form-item label="每公里价格" prop="unitPricePerMile">
            <el-input v-model="temp.unitPricePerMile" />
          </el-form-item>
          <el-form-item label="每分钟价格" prop="unitPricePerMinute">
            <el-input v-model="temp.unitPricePerMinute" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            Cancel
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createDate():UpdateDate()">
            Confirm
          </el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { getRuleList, editRule, addRule, getDicDistrict } from '@/api/rules.js'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  
  export default {
    name: 'rule',
    components: { Pagination },
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20
        },
        filteredCities: {}, // 存储筛选后的城市
        cityNameToCode: {}, // 用于存储城市名称到编码的映射
        cityCodeToName: {}, // 用于存储城市编码到名称的映射
        temp: {
          cityCode:"",
          cityName: "",
          vehicleType: "1",
          startFare: 10,
          startMile: 3,
          unitPricePerMile: 1.8,
          unitPricePerMinute: 0.5
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        downloadLoading: false
      }
    },
    created() {
      this.getDicDistrict();
      this.getList();
    },
    methods: {
      getDicDistrict() {
        getDicDistrict().then(resp => {
          const data = resp.data;
          const cityNameToCode = {};
          const cityCodeToName = {};
          for (const item of data) {
            cityNameToCode[item.addressName] = item.addressCode;
            cityCodeToName[item.addressCode] = item.addressName;
          }
          this.cityNameToCode = cityNameToCode;
          this.cityCodeToName = cityCodeToName;
        });
      },
      
      getList() {
        this.listLoading = true
        getRuleList(this.listQuery).then(response => {
          this.list = response.data.items
          this.total = response.data.total
  
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      getCityName(cityCode) {
        return this.cityCodeToName[cityCode];
      },

      getCarType(num){
        switch(num){
            case '1':
                return "轿车";
            case '2':
                return "SUV";
            case '3':
                return "MPV";
            case '4':
                return "面包车";
            case '9':
                return "其他";
            default:
                return "未知";
        }
      },
  
      loadCities(queryString, cb) {
        if (queryString === '') {
          cb(this.cityNameToCode.map(cityName => ({ value: cityName, code: this.cityNameToCode[cityName] })));
        } else {
          const results = Object.keys(this.cityNameToCode)
            .filter(city => city.includes(queryString))
            .map(cityName => ({ value: cityName, code: this.cityNameToCode[cityName] }));
          cb(results);
        }
      },
  
      handleSelect(item) {
        // 更新显示值为城市名称
        this.listQuery.cityName = item.value;
        // 同时更新实际的城市代码
        this.listQuery.cityCode = item.code;
      },
  
      handleSelectUpdate(item){
        this.temp.cityName = item.value;
        this.temp.cityCode = item.code;
      },
  
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
  
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作Success',
          type: 'success'
        })
        row.status = status
      },
      
      handleCreate() {
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        // 在添加时，清空 temp 对象，以确保不提交 ID
        this.temp = {
          cityCode:"",
          cityName: "",
          vehicleType: "1",
          startFare: 10,
          startMile: 3,
          unitPricePerMile: 1.8,
          unitPricePerMinute: 0.5
        }
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        this.dialogStatus = 'update';
        this.dialogFormVisible = true;
        this.temp = {
          cityCode: row.cityCode,
          cityName: this.getCityName(row.cityCode),
          vehicleType: row.vehicleType,
          startFare: row.startFare,
          startMile: row.startMile,
          unitPricePerMile: row.unitPricePerMile,
          unitPricePerMinute: row.unitPricePerMinute
        };
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate();
        });
      },
  
      handleDelete(row, index) {
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      },
  
      createDate() {
        console.log(this.temp);
        addRule(this.temp).then(() => {
          this.dialogFormVisible = false;
          this.getList();
        }).catch(error => {
          console.error('Failed to create item:', error);
        });
      },
  
      UpdateDate() {
        console.log(this.temp);
        editRule(this.temp).then(() => {
          this.dialogFormVisible = false;
          this.getList();
        }).catch(error => {
          console.error('Failed to update item:', error);
        });
      },
    },
  
    watch: {
      'listQuery.cityName'(newVal) {
        // 当新值为空时，也将城市代码设置为空
        if (!newVal) {
          this.listQuery.cityCode = '';
        }
      }
    }
  }
  </script>